#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cherrypy
from cherrypy import request, HTTPRedirect
from cherrypy.lib import http


class VirtualHost(object):
    """A virtual host scheme for CherryPy that works with RoutesDispatcher.
    Based on cherrypy._cpdispatch.VirtualHost():
    http://svn.cherrypy.org/trunk/cherrypy/_cpdispatch.py
    
    Why is this one better? The original associates domains with path prefixes.
    This one associates domains with apps. The apps must know their own
    dispatch. (and mountpoint?)
    """
    def __init__(self, map={}):
        self.map = map
        self.dispatch = cherrypy._cpdispatch.Dispatcher()
    
    def add(self, app, domains):
        for domain in domains:
            self.map[domain] = app
    
    def __call__(self, path_info):
        header = request.headers.get
        domain = header('Host', '')
        dest = self.map.get(domain, None)
        if dest:
            if isinstance(dest, basestring):
                raise HTTPRedirect("http://" + dest + path_info)
            else:  # If the found dest is not string, it must be an app.
                # At least for a RoutesDispatcher, this line is not good:
                # path_info = http.urljoin(app.mountpoint, path_info)
                request.app = dest
                # print request.wsgi_environ
                return dest.dispatch(path_info)
        else:
            return self.dispatch(path_info)
